package com.ruoyi.web.controller.basicInformation;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.basicInformation.bo.TElectronicFenceObjectAddBo;
import com.ruoyi.system.basicInformation.domain.TElectronicFence;
import com.ruoyi.system.basicInformation.service.ITElectronicFenceObjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.basicInformation.vo.TElectronicFenceVo;
import com.ruoyi.system.basicInformation.bo.TElectronicFenceQueryBo;
import com.ruoyi.system.basicInformation.bo.TElectronicFenceAddBo;
import com.ruoyi.system.basicInformation.bo.TElectronicFenceEditBo;
import com.ruoyi.system.basicInformation.service.ITElectronicFenceService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * 电子围栏Controller
 *
 * @author ruoyi
 * @date 2021-05-20
 */
@Api(value = "电子围栏控制器", tags = {"电子围栏管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/basicInformation/fence")
public class TElectronicFenceController extends BaseController {

    private final ITElectronicFenceService iTElectronicFenceService;
    private final ITElectronicFenceObjectService itElectronicFenceObjectService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询电子围栏列表
     */
    @ApiOperation("查询电子围栏列表")
//    @PreAuthorize("@ss.hasPermi('basicInformation:fence:list')")
    @GetMapping("/list")
    public TableDataInfo<TElectronicFenceVo> list(TElectronicFenceQueryBo bo) {
        startPage();
        List<TElectronicFenceVo> list = iTElectronicFenceService.queryList(bo);
        return getDataTable(list);
    }

    @Log(title = "电子围栏导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TElectronicFence> util = new ExcelUtil<TElectronicFence>(TElectronicFence.class);
        List<TElectronicFence> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = iTElectronicFenceService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<TElectronicFence> util = new ExcelUtil<TElectronicFence>(TElectronicFence.class);
        return util.importTemplateExcel("电子围栏数据");
    }

    /**
     * 导出电子围栏列表
     */
    @ApiOperation("导出电子围栏列表")
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:export')")
    @Log(title = "电子围栏", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<TElectronicFenceVo> export(TElectronicFenceQueryBo bo) {
        List<TElectronicFenceVo> list = iTElectronicFenceService.queryList(bo);
        ExcelUtil<TElectronicFenceVo> util = new ExcelUtil<TElectronicFenceVo>(TElectronicFenceVo.class);
        return util.exportExcel(list, "电子围栏");
    }

    /**
     * 获取电子围栏详细信息
     */
    @ApiOperation("获取电子围栏详细信息")
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:query')")
    @GetMapping("/{id}")
    public AjaxResult<TElectronicFenceVo> getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(iTElectronicFenceService.queryById(id));
    }

    /**
     * 新增电子围栏
     */
    @ApiOperation("新增电子围栏")
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:add')")
    @Log(title = "电子围栏", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult<Void> add(@RequestBody TElectronicFenceAddBo bo) {
        if ("1".equals(iTElectronicFenceService.checkNameUnique(bo.getName(),0))) {
            return AjaxResult.error("新增电子围栏：'" + bo.getName() + "'失败，已存在");
        }
        Integer id = iTElectronicFenceService.insertByAddBo(bo);
        if (id > 0) {
            insetFenceObject(id, bo.getUserIds(),"1");
            insetFenceObject(id, bo.getCarIds(),"2");
            insetFenceObject(id, bo.getShipIds(),"3");
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 修改电子围栏
     */
    @ApiOperation("修改电子围栏")
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:edit')")
    @Log(title = "电子围栏", businessType = BusinessType.UPDATE)
    @PutMapping()
    public AjaxResult<Void> edit(@RequestBody TElectronicFenceEditBo bo) {
        if ("1".equals(iTElectronicFenceService.checkNameUnique(bo.getName(),bo.getId().intValue()))) {
            return AjaxResult.error("修改电子围栏：'" + bo.getName() + "'失败，已存在");
        }
        if (iTElectronicFenceService.updateByEditBo(bo)) {
            insetFenceObject(bo.getId(), bo.getUserIds(),"1");
            insetFenceObject(bo.getId(), bo.getCarIds(),"2");
            insetFenceObject(bo.getId(), bo.getShipIds(),"3");
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    private void insetFenceObject(Integer fenceId, String objIds,String ObjectType) {
        TElectronicFenceObjectAddBo bo1 = null;
        if (StrUtil.isNotBlank(objIds)) {
            String[] ids = objIds.split(",");
            for (String i : ids) {
                bo1 = new TElectronicFenceObjectAddBo();
                bo1.setElectronicFenceId(fenceId);
                bo1.setObjectId(Integer.parseInt(i));
                bo1.setObjectType(ObjectType);
                itElectronicFenceObjectService.insertByAddBo(bo1);
            }
        }
    }

    /**
     * 删除电子围栏
     */
    @ApiOperation("删除电子围栏")
    @PreAuthorize("@ss.hasPermi('basicInformation:fence:remove')")
    @Log(title = "电子围栏", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@PathVariable Long[] ids) {
        return toAjax(iTElectronicFenceService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }
//
//    @ApiOperation("判断点是否在电子围栏内")
//    @PreAuthorize("@ss.hasPermi('basicInformation:fence:query')")
//    @Log(title = "电子围栏")
//    @GetMapping("/checkIsExistsForXY/{id}")
//    public AjaxResult<Boolean> checkIsExistsForXY(@PathVariable Long id) {
//        return AjaxResult.success(iTElectronicFenceService.checkIsExistsForXY(132.19423922614106,45.585792002342686,id));
//    }

}
